var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var ejs = require('ejs');
var router = express.Router();

var index = require('./routes/index');
var users = require('./routes/users');
var random = require('./routes/random');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('sessionId'));
//通过 Express 内置的 express.static 可以方便地托管静态文件，例如图片、CSS、JavaScript 文件等。
// http://127.0.0.1:3000/images/1.jpg
app.use(express.static(path.join(__dirname, 'public')));
//以通过带有 “/static” 前缀的地址来访问 public 目录下面的文件
// http://127.0.0.1:3000/static/images/1.jpg
// app.use('/static', express.static(path.join(__dirname, 'public')));

app.use(session({
  secret: 'sessionId',
  resave: true,
  saveUninitialized:true
}))


app.use(function(req, res, next){ 
  res.locals.session = req.session;
  next();
});
app.use('/', index);
app.use('/user', users);
app.use('/random', random);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  console.log(err);
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
